/**
 * @ngdoc module
 * @name report.controllers
 * @description
 *  汇报模块控制器
 */

angular.module('report.controllers', [])

/**
 * @ngdoc controller
 * @name ReportIndexCtrl
 * @module report.controllers
 * @description
 *   汇报首页控制器
 */
  .controller('ReportIndexCtrl', function($scope, $ionicModal, $ionicLoading, $localstorage, $state, $timeout, uniqueFilter, mapFilter, Utils, IbPopup, Report){
    var LOCAL_SETTINGS_KEY = 'report.settings';
    var localReportSettings = $localstorage.getObject(LOCAL_SETTINGS_KEY);

    $scope.order = false;
    $scope.loading = true;

    //从远程数据筛选出本地所不包含的所有子项。
    function filterItem(originTempArr, localTempArr) {
       var localTids = mapFilter(localTempArr, 'tid');
      return originTempArr
        .filter(function (item) {
          return localTids.indexOf(item.tid) === -1;
        });
    }

    //模板排序
    function orderTpl(originTemp, localTemp) {
      //拿到新添加的数据
      var diffArr = filterItem(originTemp, localTemp);
      // 如果远程数据有本地数据没有的项目则返回本地数据和新数据合集
      return diffArr.length ? localTemp.concat(diffArr) : localTemp;
    };

    // 获取未读数
    function updateUnreadCount() {
      Report.getUnreadCount().success(function(res){
        if(res.isSuccess){
          $scope.unreadCount = res.data.unread
        }
      })
    }

    //获取可用模板
    function updateUserTemplate() {
      $ionicLoading.show();
      Report.getUserTemplate().success(function(res){
        if(res.isSuccess){
          $scope.loading = false;
          if(localReportSettings){
            $scope.templates = orderTpl(res.data, localReportSettings);
          } else {
            $scope.templates = res.data;
          }

          $scope.isSet = res.isSet
        } else {
          Utils.promptNoPermission();
        }
      }).finally($ionicLoading.hide)
    }

    //离开的时候关闭模板
    function closeMode(scope, modal){
      scope.$on('$ionicView.leave', modal.hide.bind(modal));
      scope.$on('$destroy', modal.remove.bind(modal))
    }

    //打开管理模板
    $scope.openManageModel = function(){
      $ionicModal.fromTemplateUrl('templates/report/report-manage-modal.html',{
        scope: $scope,
        animation: 'slide-in-up'
      })
        .then(function(modal){
          $scope.manageModel = modal;
          $scope.manageModel.show();

          //设置模板的数据
          $scope.settingTpls = $scope.templates;

          $scope.openOrderList = function(){
            $scope.settingTpls = $scope.templates;
            //模板排序
            $scope.moveTpl = function(tpl, fromIndex, toIndex) {
              //把该项移动到数组中
              $scope.settingTpls.splice(fromIndex, 1);
              $scope.settingTpls.splice(toIndex, 0, tpl);
              $localstorage.setObject(LOCAL_SETTINGS_KEY, $scope.settingTpls)
            };

            $scope.orderFinish = function() {
              $scope.manageModel.hide();
              $scope.templates = $scope.settingTpls;
            }
          };

          closeMode($scope, modal);
        })
    };

    //打开设置模板
    $scope.openSettingModel = function(tid){
      $ionicModal.fromTemplateUrl('templates/report/report-setting-modal.html',{
        scope: $scope,
        animation: 'slide-in-up'
      })
        .then(function(modal){
          $scope.settingModel = modal;
          $scope.settingModel.show();
          $scope.collection = [];
          $scope.manageTypes  = [];
          $scope.uptype = {};
          $scope.formData = {};
          var updateList = [];

          //获取主管类型
          Report.getcharge().success(function(res){
            if(res.isSuccess){
              $scope.managers = res.data;
            }
          });

          //取消删除主管类型
          $scope.outRemoveTypeMode = function(){
            $scope.removeTypeMode = false;
          };

          $scope.removeTypeMode = false;
          //删除主管类型
          $scope.toRemoveTypeMode = function($event){
            $scope.removeTypeMode = true;
            $event.stopPropagation();
          };


          //打开选择主管列表
          $scope.openSelectManagerModal = function(){
            $ionicModal.fromTemplateUrl('templates/report/report-select-manager-modal.html',{
              scope: $scope,
              animation: 'slide-in-up'
            })
              .then(function(modal){
                $scope.chargeModel = modal;
                $scope.chargeModel.show();
                var manageTypes;

                // 判断是否已有选中的类型，如果是则自动选中；
                if($scope.manageTypes.length > 0){
                  manageTypes = ([].concat($scope.manageTypes.map(function(item){
                    return item.uptype
                  })));

                  angular.forEach($scope.managers, function(type){
                    for(var i = 0; i < manageTypes.length; i++){
                      if(type.uptype == manageTypes[i]){
                        $scope.uptype[type.uptype] = true;
                      }
                    }
                  })
                };

                $scope.addManager = function(){
                  $scope.chargeModel.hide();
                  $scope.manageTypes = [];

                  angular.forEach($scope.managers, function(type) {
                    // 判断管理人员是否被选中
                      if($scope.uptype[type.uptype]) {
                        $scope.manageTypes.push(type);
                        $scope.manageTypeids = ([].concat($scope.manageTypes.map(function(item){
                          return item.uptype
                        }))).join(',');
                      }
                  });
                };

                closeMode($scope, modal);
              })
          };

          function alert(prompt){
            IbPopup.alert({ title: prompt })
              .then(function(flag){
                if(flag){
                  $scope.settingModel.hide();
                  $state.go('report.index');
                }
              })
          }

          $scope.removeType = function($event, type) {
            var index = $scope.manageTypes.indexOf(type);
            $scope.manageTypes.splice(index, 1);
            $scope.manageTypeids = ([].concat($scope.manageTypes.map(function(item){
              return item.uptype
            }))).join(',');

            if(!$scope.manageTypes.length) $scope.removeTypeMode = false;
            $event.stopPropagation();
          };


          //获取模板设置值
          $ionicLoading.show();
          Report.settemplate({ tid : tid } ).success(function(res){
            if(res.isSuccess) {
              $scope.formData.defaultShareList = res.data.uid;
              $scope.manageTypes = res.data.uptype;
              $scope.formData.defaultReceiveList = res.data.upuid;
            }
          }).finally($ionicLoading.hide);

          //设置模板
          $scope.setTemplate = function(){
            var params = {
              tid: tid,
              uid: $scope.formData.defaultShareList || '',
              uptype: $scope.manageTypeids || '',
              upuid: $scope.formData.defaultReceiveList || ''
            };

            $ionicLoading.show();
            Report.settemplate(params).success(function(res){
              if(res.isSuccess){
                IbPopup.alert({ title: '设置成功'}).then(function(){
                  $scope.openManageModel();
                })
              } else {
                alert('设置失败')
              }
            }).finally($ionicLoading.hide)
          };

          closeMode($scope, modal);
        });
    };

    //添加模板
    $scope.openAddModal = function() {
      $ionicModal.fromTemplateUrl('templates/report/report-add-modal.html',{
        scope: $scope,
        animation: 'slide-in-up'
      })
        .then(function(modal){
          $scope.addModel = modal;
          $scope.addModel.show();
          $ionicLoading.show();
          Report.getShopList().success(function(res){
            if(res.isSuccess){
              $scope.templateData = res.data;
              $scope.isAdd = res.isAdd;

              $scope.addTemplate = function(tid){
                $ionicLoading.show();
                Report.addTemplate(tid).success(function(res){
                  if(res.isSuccess){
                    $scope.addModel.hide();
                    $timeout(updateUserTemplate);
                    $state.go('report.index');
                  }
                }).finally($ionicLoading.hide)
              };
            }
          }).finally($ionicLoading.hide)

          closeMode($scope, modal);
        });
    };

    $scope.$on('$ionicView.enter', function() {
      updateUnreadCount();
      updateUserTemplate()
    });
  })

/**
 * @ngdoc controller
 * @name ReportFormCtrl
 * @module report.controllers
 * @description
 *   汇报-表单（创建/编辑） 的控制器
 */
  .controller('ReportFormCtrl', function($scope, $q, $stateParams, $ionicLoading, $ionicHistory, $state, Utils, External, CommonApi, IbPopup, mapFilter, fileSizeFilter, dateFilter, ReportUtils, Report){
    var tid = $stateParams.tid,
      repid = $stateParams.repid;
    //如果有tid 是新建汇报，否则是编辑汇报；
    var data =  tid ? { tid: tid } : { repid: repid };
    $ionicLoading.show();
    Report.getTemplateData(data).success(function(res){
      $ionicLoading.show();
      if(res.isSuccess){
        $scope.formData = {
          subject: '',
          toid: '',
          attachmentid: '',
          remark: '',
          place: '',
          status: 1,
          fields: []
        };
        var tpl = res.data.template;
        $scope.subject = res.data.template.subject;
        $scope.formData.tid = tpl.tid || '';
        $scope.formData.fields = res.data.templateField || '';
        $scope.formData.toid = tpl.defaultuid || '';
        $scope.formData.remark = tpl.remark || '';
        $scope.accessories = tpl.attach || [];
        //编辑汇报时
        if(repid){
          $scope.formData.repid = tpl.repid || '';
          angular.forEach($scope.formData.fields, function(item){
            if(item.fieldtype == '4'|| item.fieldtype == '6'){
              item.content = new Date(item.content);
            } else if(item.fieldtype == '5'){
              //因为只取时分的数据，new Date需要传入完整的格式；
              item.content = new Date( "1970-01-01 " + item.content )
            } else if(item.fieldtype == '3'){
              if (!isNaN(Number(+item.content))){
                item.content = +item.content
              } else{
                item.content = 0;
              }
            }
          });
        }

        // 提交汇报
        $scope.submit = function(){
          // 图片id
          $scope.formData.attachmentid = $scope.accessories
            .map(function(annex) {
              return annex.aid;
            })
            .join(',');
          var formData = changeDataType($scope.formData);
          $ionicLoading.show();
          Report.saveReport(formData).success(function(res){
            if(res.isSuccess){
              tid ? $state.go('report.send'): $state.go('report.view',{ repid: repid });
            } else {
              alert(res.msg)
            }
          }).finally($ionicLoading.hide)
        };

        $scope.saveDraft = function(){
          if($scope.reportForm.$dirty){
            IbPopup.confirm({ title: '你还未发布汇报，是否保存' }).then(function(flag) {
              if(flag){
                $scope.formData.status = 0;
                var formData = changeDataType($scope.formData);
                $ionicLoading.show();
                Report.saveReport(formData).success(function(res){
                  if(res.isSuccess){
                    $ionicHistory.goBack();
                  }
                }).finally($ionicLoading.hide)
              } else{
                $ionicHistory.goBack();
              }
            })
          } else {
            $ionicHistory.goBack();
          }
        }
      }
    }).finally($ionicLoading.hide);

    function changeDataType (formData){
      formData = angular.merge({}, formData);

      //按后端要求提交前转数据格式
      angular.forEach(formData.fields, function(item){
        if(!item.content){
          item.content = '';
        }
       //字段类型，1表示长文本，2表示短文本，3表示数字，4表示日期与时间，5表示时间，6表示日期，7表示下拉, 8表示富文本(目前用长文本替代)
        if(item.fieldtype == 3){
          item.content = '' + item.content;
        } else if(item.fieldtype == 4){
          item.content = dateFilter(item.content, 'yyyy-MM-dd HH:mm') || '';
        } else if(item.fieldtype == 5){
          item.content = dateFilter(item.content, 'HH:mm') || '';
        } else if(item.fieldtype == 6){
          item.content = dateFilter(item.content, 'yyyy-MM-dd') || '';
        } else if(item.fieldtype == 7){
          item.fieldvalue = item.fieldvalue.join(',');
        }
      });

      return formData;
    };

    //添加图片
    $scope.addImage = function(evt){
      $scope.uploading = true;
      angular.forEach(evt.target.files, function(file) {
        var temp = {
          name: file.name,
          size: fileSizeFilter(file.size),
          type: file.type.split('/')[1],
          uploading: true,
          cancel: null
        };
        temp.cancel = $q.defer();
        temp.index = $scope.accessories.length;
        $scope.accessories.push(temp);
        $scope.$applyAsync();
        var formData = new FormData();
        formData.append('Filedata[]', file);
        CommonApi.uploadAttach(formData, { timeout: temp.cancel.promise })
          .then(function(res){
            var data = res.data;
            if(data.isSuccess){
              // 上传成功补上aid信息
              var uploadedImage = data.data[0];
              temp.aid = uploadedImage.aid;
            } else {
              // 上传不成功删除
              $scope.accessories.splice(temp.index, 1);
            }
          })
          .catch(function(err) {
            // 上传失败删除
            $scope.accessories.splice(temp.index, 1);
          })
          .finally(function() {
            temp.uploading = false;
            // 正在上传的图片
            var uploadingAccessories = $scope.accessories
              .filter(function(annex) {
                return annex.uploading;
              });
            // 没有了正在上传的图片关闭总loading
            if (!uploadingAccessories.length) {
              $scope.uploading = false;
            }
          });
      });
    };

    // 移除图片
    $scope.removeImage = function(index) {
      IbPopup.confirm({ title: '确定要删除该图片吗？' }).then(function(flag) {
        if(flag) {
          $scope.accessories.splice(index, 1);
        }
      });
    };
  })

/**
 * @ngdoc controller
 * @name ReportReceiveCtrl
 * @module report.controllers
 * @description
 *   汇报列表-我收到的控制器
 */
  .controller('ReportReceiveCtrl', function($scope, $rootScope, $ionicScrollDelegate, $ionicLoading, dateFilter, IbPopup, SearchModal, ReportUtils, Report){
    $scope.activeTab = 'unread';
    $scope.loading = true;
    var params = {
      limit: 10 ,
      offset: 0 ,
      type:'unread'
    };

    $scope.groupByTime = function(item) {
      return dateFilter(item.addtime * 1000, 'EEEE');
    };

    $scope.readReport = function(report){
      report.isreview = '1';
    };

    $scope.setTab = function(type) {
      $ionicScrollDelegate.$getByHandle('reportReceiveListScroll').scrollTop();
      $scope.list = [];
      $scope.loading = true;
      $scope.activeTab = type || 'unread';
      params.offset = 0;
      params.type = type === 'unread' ? 'unread':'receive';
      ReportUtils.getList($scope, params);
    };

    $scope.addRead = function(){
      $ionicLoading.show();
      Report.allRead().success(function(res){
        if(res.isSuccess){
          params.type = 'receive';
          $scope.activeTab = 'all';
          ReportUtils.getList($scope, params);
          IbPopup.alert({ title: '全部标记已读' });
        }
      }).finally($ionicLoading.hide);
    };

    $scope.loadMore = function(){
      var type =  $scope.activeTab;
      params.offset = $scope.list.length;
      params.type = type === 'unread' ? 'unread':'receive';
      $ionicLoading.show();
      Report.getList(params).success(function(res){
        if(res.isSuccess){
          $scope.list = $scope.list.concat(res.data.list);
        }
      }).finally($ionicLoading.hide)
    };

    $scope.search = new SearchModal({
      scope: $scope,
      searchFunc: function(params){
        return Report.getList({
          type: 'receive',
          limit: 99,
          offset: 0,
          keyword:{
            subject: params.key
          }
        });
      }
    });

    $scope.refresh = function(){
      params.offset = 0;
      ReportUtils.getList($scope, params);
    };

    ReportUtils.getList($scope, params);
  })

/**
 * @ngdoc controller
 * @name ReportSendCtrl
 * @module report.controllers
 * @description
 *   汇报列表-我发出的控制器
 */
  .controller('ReportSendCtrl', function($scope, $rootScope, $ionicLoading, dateFilter, SearchModal, ReportUtils, Report){
    $scope.loading = true;
    var params = {
      limit: 10 ,
      offset: 0 ,
      type:'send'
    };

    $scope.groupByTime = function(item) {
      return dateFilter(item.addtime * 1000, 'EEEE');
    };

    $scope.loadMore = function(){
      params.offset = $scope.list.length;
      $ionicLoading.show();
      Report.getList(params).success(function(res){
        if(res.isSuccess){
          $scope.list = $scope.list.concat(res.data.list);
        }
      }).finally($ionicLoading.hide)
    };

    $scope.search = new SearchModal({
      scope: $scope,
      searchFunc: function(params){
        return Report.getList({
          type: 'send',
          limit: 99,
          offset: 0,
          keyword:{
            subject: params.key
          }
        });
      }
    });

    $scope.refresh = function(){
      params.offset = 0;
      ReportUtils.getList($scope, params);
    };

    ReportUtils.getList($scope, params);
  })

/**
 * @ngdoc controller
 * @name ReportViewCtrl
 * @module report.controllers
 * @description
 *   汇报详情页控制器
 */
  .controller('ReportViewCtrl', function($scope, $rootScope, $stateParams, $ionicModal, $ionicLoading, $ionicActionSheet, $state, $ionicHistory, IbPopup, uniqueFilter, userInfoFilter, Report){
    $scope.currentUserUid = $rootScope.user.uid;
    $ionicLoading.show();
    Report.showReport($stateParams.repid).success(function(res){
      if(res.isSuccess){
        $scope.report = res.data;
        $scope.report.readers = res.data.reader;

        //评论参数
        var commentData = {
          type: 'comment',
          rowid: $scope.report.repid,
          offset: 0,
          limit: 999
        };

        //获取评论列表
        function getCommentList(){
          $ionicLoading.show();
          Report.getComments(commentData).success(function(res){
            $ionicLoading.hide();
            $scope.commentList = res.data.lists;
          });
        }

        $scope.openComment = function(type, cm){
          $ionicModal.fromTemplateUrl('templates/report/report-comment.html',{
            scope: $scope,
            animation:'slide-in-up'
          })
            .then(function(modal){
              $scope.comment = {};
              $scope.commentModal = modal;
              $scope.comment.isStampsBoxShow = false;
              $scope.commentModal.show();

              Report.getStamp().success(function(res){
                if(res.isSuccess){
                  $scope.report.stamps = res.data;
                }
              });

              if (type === 'reply'){
                $scope.comment.content = cm.touid ? '回复 @' + userInfoFilter(cm.uid,'realname') + ' : ': ''
              }

              $scope.submit = function(){
                var params = {
                  type:type ,
                  content: $scope.comment.content,
                  moduleuid: $scope.user.uid
                };

                if(type === 'comment'){
                  params.rowid = $scope.report.repid;
                } else {
                  params.tocid = cm.cid;
                  // 如果直接回复评论，则
                  if(cm.tocid === '0') {
                    params.rowid = cm.cid;
                    // 否则，如果回复评论下的回复，则
                  } else {
                    params.rowid = cm.rowid;
                  }
                }

                Report.addComment(params).success(function(res){
                  if($scope.comment.stamp){
                    var params = {
                      repid: $stateParams.repid,
                      stampid: $scope.comment.stamp.stampid
                    };
                    Report.setStamp(params)
                  }
                  Report.showReport($stateParams.repid).success(function(res) {
                    if (res.isSuccess) {
                      $scope.report.stamp = res.data.stamp;
                    }
                  });
                  $scope.commentModal.hide();
                  $ionicLoading.show();
                  getCommentList()
                })
              };
            })
        };

        $scope.openCommentDetail = function(){
          $ionicModal.fromTemplateUrl('templates/report/report-comment-detail.html',{
            scope: $scope,
            animation: 'slide-in-up'
          })
            .then(function(modal) {
              $scope.commentTetailModal = modal;
              $scope.commentTetailModal.show();
              getCommentList()
            })
        };

        $scope.openReaderDetail = function(){
          $ionicModal.fromTemplateUrl('templates/report/report-reader-detail.html',{
            scope: $scope,
            animation: 'slide-in-up'
          })
            .then(function(modal) {
              $scope.readerTetailModal = modal;
              $scope.readerTetailModal.show();
            })
        };

        $scope.operateMore = function(){
          var hideSheet = $ionicActionSheet.show({
            buttons: [
              { text: '编辑' }
            ],
            destructiveText: '删除',
            cancelText: '取消',
            buttonClicked: function(index) {
              if(index === 0){
                $state.go('report.form',{ repid: $scope.report.repid })
              }
            },
            destructiveButtonClicked: function(){
              IbPopup.confirm({ title: '确认删除汇报？'}).then(function(flag){
                if(flag){
                  $ionicLoading.show();
                  Report.delReport($scope.report.repid).success(function(res){
                    if(res.isSuccess){
                      $ionicHistory.goBack();
                    }
                  }).finally($ionicLoading.hide);
                }
              });
            }
          });
        };

        getCommentList();
      }
    }).finally($ionicLoading.hide)
  });
